package com.edu.koudingmusic;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;

import com.edu.koudingmusic.services.PlayService;
import com.edu.koudingmusic.tools.Constant;

public abstract class BaseActivity extends FragmentActivity {

    public PlayService mPlayService;



    private boolean isBind = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            PlayService.PlayController controller = (PlayService.PlayController) service;
            mPlayService = controller.getPlayService();
            mPlayService.setMusicUpdateListener(mMusicUpdateListener);
            mMusicUpdateListener.onChange(mPlayService.getCurrentPosition());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mPlayService = null;
            isBind = false;
        }
    };

    private PlayService.MusicUpdateListener mMusicUpdateListener = new PlayService.MusicUpdateListener() {
        @Override
        public void onPublish(int progress) {
            publish(progress);
        }

        @Override
        public void onChange(int position) {
            change(position);
        }
    };

    public abstract void publish(int progress);
    public abstract void change(int position);

    // 绑定服务
    public void bindPlayService() {
        if (!isBind) {
            Intent intent = new Intent(this, PlayService.class);
            bindService(intent, conn, Context.BIND_AUTO_CREATE);
            isBind = true;
        }
    }

    // 解除绑定服务
    public void unBindPlayService() {
        if (isBind) {
            unbindService(conn);
            isBind = false;
        }
    }
}
